<template>
  <el-aside
    :class="
      'layout-aside-' +
      config.layout.layoutMode +
      ' ' +
      (config.layout.shrink ? 'shrink' : '')
    "
  >
    <div class="fold" @click="onMenuCollapse" style="cursor: pointer">
      <div v-if="!config.layout.overviewCollapse">工作中心</div>
      <!-- <Menu @click="onMenuCollapse" style="width: 1.3em; height: 1.3em" /> -->
      <Icon
        size="15"
        name="fa fa-filter"
        style="cursor: pointer"
        title="关键词过滤"
      />
    </div>
    <el-input
      v-if="!config.layout.overviewCollapse"
      v-model="filterText"
      placeholder="输入关键字进行过滤"
      style="background: whitesmoke"
    />
    <el-scrollbar ref="verticalMenusRef" class="vertical-menus-scrollbar">
      <el-tree
        v-if="!config.layout.overviewCollapse"
        ref="treeRef"
        class="filter-tree"
        :data="state.stationOptions"
        :props="defaultProps"
        node-key="id"
        show-checkbox
        :load="loadNode"
        lazy
        @check="handleCheckChange"
        :filter-node-method="filterNode"
      />
    </el-scrollbar>
  </el-aside>
</template>
<script lang="ts" setup>
import {
  ref,
  onMounted,
  computed,
  onBeforeUnmount,
  watch,
  reactive,
  inject,
} from "vue";
import { ElTree, ElScrollbar } from "element-plus";
import { useConfig } from "@/store/config"; //后台布局相关仓库
import { useRegion } from "@/store/backend/SysM/region";
import type Node from "element-plus/es/components/tree/src/model/node";
import _ from "lodash";

interface Region {
  address: string | null;
  addressDetail: string | null;
  areaFlag: string | null;
  areaId: number;
  areaName: string | null;
  areaNo: string | null;
  children: Region[];
  createBy: string | null;
  createTime: string | null;
  endTime: string | null;
  params: any;
  parentId: number;
  searchValue: string | null;
  startTime: string | null;
  updateBy: string | null;
  updateTime: string | null;
}
const filterText = ref("");
const treeRef = ref<InstanceType<typeof ElTree>>();
const config = useConfig();
const region = useRegion();
const equipUnit = inject("equipUnit") as any;
const schedule = inject("schedule") as any;
const dept = inject("dept") as any;

const verticalMenusRef = ref<InstanceType<typeof ElScrollbar>>();
// const baTable = inject("baTable") as baTableClass;

const defaultProps = {
  children: "children",
  label: "label",
  isLeaf: "leaf",
};

// 关键词过滤
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.includes(value);
};

const state: { regionOptions: anyObj[]; stationOptions: any[] } = reactive({
  regionOptions: [], //区域列表
  stationOptions: [], //工作中心列表
});

// 传递给父组件的值
const emit = defineEmits(["on-chooseRegion"]);
//选择区域后调取区域数据展示
const handleCheckChange = (row: Region, node: any) => {
  console.log("row", row, "node", node);
  //保存工作中心数据便于修改工厂日历刷新工厂日历记录数据
  schedule.$patch((state: any) => {
    state.backupSearch = row;
  });
  //传递给父组件
  emit("on-chooseRegion", row, node);
};

// 控制菜单是否折叠
const onMenuCollapse = () => {
  getDeptData();
  config.overViewsetLayout("overviewCollapse", !config.layout.overviewCollapse);
};

//针对侧边栏菜单高度让滚动条自适应
const overviewMenusScrollbarHeight = computed(() => {
  // 加上了50px的头部距离
  let menuTopBarHeight = 50;
  if (config.layout.layoutMode == "Default") {
    //32为aside上下margin
    return "calc(100vh - " + (172 + menuTopBarHeight) + "px)";
  } else {
    return "calc(100vh - " + (140 + menuTopBarHeight) + "px)";
  }
});

const menuWidth = computed(() => config.overviewMenuWidth());

interface Tree {
  name: string;
  leaf?: boolean;
}

//el-tree懒加载
const loadNode = (node: Node, resolve: (data: any[]) => void) => {
  console.log("懒加载", node);
  let hasChild = true;

  if (node.level === 0) {
    return resolve([]);
  }
  if (node.level > 1) {
    if (node.data.children && node.data.children.length !== 0) {
    } else {
      //如果没有子级节点开始将设备数据加载
      return getDevicesOfDeptId(node.data).then((res: any) => {
        return resolve(res);
      });
    }
    hasChild = false;
  }
  let newArr = _.cloneDeep(state.stationOptions[0].children);
  let resArr: any[] = [];

  console.log("resArr", resArr, newArr);
  if (hasChild) {
    resArr = getTreeOfStation(newArr);
  } else {
    if (node.data.children.length == 0) {
      resArr = [];
    } else {
      resArr = node.data.children;
    }
  }
  setTimeout(() => {
    resolve(resArr);
  }, 500);
};
//获取部门下设备数据
const getDevicesOfDeptId = (filter: any) => {
  return new Promise((resolve: any, reject: any) => {
    equipUnit
      .getEquipmentByRole({ name: filter.label, deptId: filter.id })
      .then((res: any) => {
        let resArr: any[] = [];
        res.forEach((item: any) => {
          resArr.push({
            label: item.equipmentName, //设备名称
            id: item.id, //设备id
            type: "equip",
            equipmentCode: item.equipmentCode, //设备编码
            deptId: item.deptId, //设备所在部门id
            leaf: false,
          });
        });
        resolve(resArr);
      });
  });
};
//遍历原始部门数据据
const getTreeOfStation = (data: any[]) => {
  let resArr: any[] = [];
  console.log("getTreeOfStation", data);

  if (data.length == 0) return data;
  if (data.length > 0) {
    data.forEach((item: any) => {
      if (item.children && item.children.length > 0) {
        item.children = getTreeOfStation(item.children);
      }
      resArr.push({
        label: item.label,
        ancestors: item.ancestors,
        id: item.id,
        type: "dept",
        children: item.children,
      });
    });
  }
  return resArr;
};

// 获取部门数据
const getDeptData = () => {
  dept.getDept().then((res: any) => {
    state.stationOptions = res.data;
    console.log("stationOptions", res);
  });
};

onMounted(() => {
  getDeptData();
});
onBeforeUnmount(() => {
  schedule.$patch((state: any) => {
    state.backupSearch = {};
  });
}),
  watch(filterText, (val) => {
    treeRef.value!.filter(val);
  });
</script>
<style lang="scss" scoped>
.layout-aside-Default {
  background-color: #fff;
  background: var(--ba-bg-color-overlay);
  margin: 0;
  height: 100%;
  box-shadow: var(--el-box-shadow-light);
  border-radius: var(--el-border-radius-base);
  overflow: hidden;
  transition: width 0.3s ease;
  width: v-bind(menuWidth);

  .vertical-menus-scrollbar {
    height: v-bind(overviewMenusScrollbarHeight);
    overflow-x: hidden;
    .filter-tree {
      display: inline-block;
    }
  }

  .fold {
    width: 100%;
    height: 50px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding: 10px;
  }
}

.layout-aside-Classic {
  background: var(--ba-bg-color-overlay);
  margin: 0;
  height: 100%;
  overflow: hidden;
  transition: width 0.3s ease;
  width: v-bind(menuWidth);

  .vertical-menus-scrollbar {
    height: v-bind(overviewMenusScrollbarHeight);
    overflow-x: hidden;
    .filter-tree {
      display: inline-block;
    }
  }

  .fold {
    width: 100%;
    height: 40px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding: 10px;
  }
}
</style>
